/**
 * UI处理模块
 */

// 全局变量
let sudokuBoard = Array(9).fill().map(() => Array(9).fill(0));
let originalBoard = Array(9).fill().map(() => Array(9).fill(0));
let solvingSteps = [];
let currentStepIndex = 0;
let selectedCell = { row: -1, col: -1 };

// DOM 元素
let boardElement, solveBtn, clearBtn, checkBtn, difficultyDisplay, statusMessage, stepControls;
let prevStepBtn, nextStepBtn, stepCounter, imageInput, previewImage, settingsBtn, fileUpload;
let sudokuGridContainer, operationButtons, uploadArea, imagePreviewContainer;
let stepByStepBtn, imagePreview, friendlyAlert, alertMessage, closeAlert, confirmAlert, manualInputBtn;
let generateBtn; // 新增的随机生成按钮

// 初始化数独网格
function initializeSudokuBoard() {
    console.log("initializeSudokuBoard 被调用");
    // 获取DOM元素
    boardElement = document.getElementById('sudokuBoard');
    solveBtn = document.getElementById('solveBtn');
    clearBtn = document.getElementById('clearBtn');
    checkBtn = document.getElementById('checkBtn');
    difficultyDisplay = document.getElementById('difficultyDisplay');
    statusMessage = document.getElementById('statusMessage');
    stepControls = document.getElementById('stepControls');
    prevStepBtn = document.getElementById('prevStepBtn');
    nextStepBtn = document.getElementById('nextStepBtn');
    stepCounter = document.getElementById('stepCounter');
    imageInput = document.getElementById('imageInput');
    previewImage = document.getElementById('previewImage');
    settingsBtn = document.getElementById('settingsBtn');
    fileUpload = document.getElementById('file-upload');
    sudokuGridContainer = document.getElementById('sudokuGridContainer');
    operationButtons = document.getElementById('operationButtons');
    uploadArea = document.getElementById('uploadArea');
    imagePreviewContainer = document.getElementById('imagePreviewContainer');
    generateBtn = document.getElementById('generateBtn'); // 获取随机生成按钮
    
    console.log("DOM元素获取完成", { boardElement, solveBtn, clearBtn });
    
    // 创建棋盘
    createBoard();
    
    // 设置事件监听器
    setupEventListeners();
}

// 创建数独棋盘
function createBoard() {
    console.log("createBoard 被调用");
    if (!boardElement) {
        boardElement = document.getElementById('sudokuBoard');
    }
    
    if (!boardElement) {
        console.error("无法找到数独棋盘元素");
        return;
    }
    
    boardElement.innerHTML = '';
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            const cell = document.createElement('div');
            // 添加适当的CSS类以确保单元格在网格中正确显示
            cell.className = 'flex items-center justify-center border border-gray-400 relative bg-white aspect-square';
            cell.dataset.row = row;
            cell.dataset.col = col;
            
            // 添加边框以区分3x3子网格
            if (row % 3 === 0) {
                cell.classList.add('border-t-2', 'border-t-gray-800');
            }
            if (col % 3 === 0) {
                cell.classList.add('border-l-2', 'border-l-gray-800');
            }
            if (row === 8) {
                cell.classList.add('border-b-2', 'border-b-gray-800');
            }
            if (col === 8) {
                cell.classList.add('border-r-2', 'border-r-gray-800');
            }
            
            const input = document.createElement('input');
            input.type = 'tel'; // 使用tel类型在移动设备上显示数字键盘
            input.inputMode = 'numeric'; // 确保显示数字键盘
            input.maxLength = 1;
            input.classList.add('w-full', 'h-full', 'text-center', 'text-2xl', 'p-0', 'm-0', 'focus:outline-none', 'focus:ring-0', 'bg-transparent', 'border-0');
            
            input.addEventListener('input', (e) => handleInput(e, row, col));
            input.addEventListener('keydown', (e) => handleKeyDown(e, row, col));
            input.addEventListener('focus', () => selectCell(row, col));
            
            cell.appendChild(input);
            boardElement.appendChild(cell);
        }
    }
    
    console.log("数独棋盘创建完成");
}

// 设置事件监听器
function setupEventListeners() {
    console.log("设置事件监听器", { solveBtn, clearBtn, checkBtn, generateBtn });
    if (solveBtn) solveBtn.addEventListener('click', solveSudoku);
    if (clearBtn) clearBtn.addEventListener('click', clearBoard);
    if (checkBtn) checkBtn.addEventListener('click', checkErrors);
    if (prevStepBtn) prevStepBtn.addEventListener('click', showPrevStep);
    if (nextStepBtn) nextStepBtn.addEventListener('click', showNextStep);
    if (settingsBtn) settingsBtn.addEventListener('click', () => {
        window.location.href = 'settings.html';
    });
    // 添加随机生成按钮事件监听器
    if (generateBtn) generateBtn.addEventListener('click', function(event) {
        event.preventDefault(); // 阻止默认行为，防止页面跳转
        generateRandomSudoku();
    });
    
    console.log("事件监听器设置完成");
}

// 处理输入
function handleInput(e, row, col) {
    const value = e.target.value;
    if (value === '' || (value >= '1' && value <= '9')) {
        sudokuBoard[row][col] = value === '' ? 0 : parseInt(value);
        // 显示数独网格
        sudokuGridContainer.classList.remove('hidden');
        // 显示操作按钮
        operationButtons.classList.remove('hidden');
        updateBoardDisplay();
        updateDifficulty();
    } else {
        e.target.value = '';
        sudokuBoard[row][col] = 0;
    }
}

// 处理键盘事件
function handleKeyDown(e, row, col) {
    // 允许方向键导航
    switch (e.key) {
        case 'ArrowUp':
            if (row > 0) selectCell(row - 1, col);
            break;
        case 'ArrowDown':
            if (row < 8) selectCell(row + 1, col);
            break;
        case 'ArrowLeft':
            if (col > 0) selectCell(row, col - 1);
            break;
        case 'ArrowRight':
            if (col < 8) selectCell(row, col + 1);
            break;
        default:
            // 其他按键按正常处理
            break;
    }
}

// 选择单元格
function selectCell(row, col) {
    // 移除之前选中单元格的样式
    document.querySelectorAll('[data-row][data-col]').forEach(cell => {
        cell.classList.remove('bg-blue-100', 'shadow-inner');
    });
    
    // 添加新选中单元格的样式
    const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
    if (cell) {
        cell.classList.add('bg-blue-100');
        selectedCell = { row, col };
        
        // 聚焦到输入框
        const input = cell.querySelector('input');
        if (input) {
            input.focus();
        }
    }
}

// 更新棋盘显示
function updateBoardDisplay() {
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const input = cell.querySelector('input');
            const value = sudokuBoard[row][col];
            
            input.value = value === 0 ? '' : value;
            
            // 更新样式类
            input.classList.remove('bg-gray-200', 'text-gray-800', 'text-red-600', 'text-blue-600', 'text-green-600', 'font-bold', 'text-gray-400');
            
            // 区分三种情况：
            // 1. OCR识别填充的题目数字 - 黑色粗体
            // 2. 手工输入的题目数字 - 浅灰不加粗
            // 3. 程序求解得出的数字 - 蓝色不加粗
            if (value !== 0) {
                if (originalBoard[row][col] !== 0 && originalBoard[row][col] === sudokuBoard[row][col]) {
                    // OCR识别填充的题目数字 - 黑色粗体
                    input.classList.add('text-gray-800', 'font-bold');
                } else if (originalBoard[row][col] !== 0 && originalBoard[row][col] !== sudokuBoard[row][col]) {
                    // 程序求解得出的数字 - 蓝色不加粗
                    input.classList.add('text-blue-600');
                } else if (originalBoard[row][col] === 0) {
                    // 手工输入的题目数字 - 浅灰不加粗
                    input.classList.add('text-gray-400');
                } else {
                    // 默认情况（应该是求解得出的数字）- 蓝色不加粗
                    input.classList.add('text-blue-600');
                }
            }
        }
    }
}

// 更新难度显示
function updateDifficulty() {
    const difficulty = evaluateDifficulty(sudokuBoard);
    difficultyDisplay.textContent = `难度: ${difficulty}`;
}

// 更新状态消息显示
function updateStatusMessage(content, className = '', autoHide = false, hideDelay = 5000) {
    if (statusMessage && content) {
        statusMessage.innerHTML = content;
        if (className) {
            statusMessage.className = className;
        }
        // 显示提示信息区域
        const hintArea = document.getElementById('hintArea');
        if (hintArea) hintArea.classList.remove('hidden');
        
        // 如果需要自动隐藏，设置定时器
        if (autoHide) {
            setTimeout(() => {
                statusMessage.textContent = '';
                if (hintArea) hintArea.classList.add('hidden');
            }, hideDelay);
        }
    } else if (statusMessage) {
        statusMessage.textContent = '';
        // 隐藏提示信息区域
        const hintArea = document.getElementById('hintArea');
        if (hintArea) hintArea.classList.add('hidden');
    }
}

// 显示Toast消息
function showToast(message, type = 'info', duration = 3000) {
    const toastContainer = document.getElementById('toastContainer');
    
    // 创建Toast元素
    const toast = document.createElement('div');
    toast.className = `toast ${type} show`;
    toast.innerHTML = message;
    
    // 添加到容器
    toastContainer.appendChild(toast);
    
    // 设置定时器自动移除
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, duration);
}

// 显示手动录入界面
function showManualInput(event) {
    console.log("手动录入按钮被点击，事件对象:", event);
    // 阻止默认行为（如果有）
    if (event) {
        event.preventDefault();
    }
    
    try {
        // 隐藏上传区域
        uploadArea.classList.add('hidden');
        // 显示数独网格
        sudokuGridContainer.classList.remove('hidden');
        // 显示操作按钮
        operationButtons.classList.remove('hidden');
        
        // 清空棋盘但不隐藏网格和按钮
        sudokuBoard = Array(9).fill().map(() => Array(9).fill(0));
        originalBoard = Array(9).fill().map(() => Array(9).fill(0));
        updateBoardDisplay();
        updateStatusMessage('', '');
        difficultyDisplay.textContent = '难度: 未知';
        stepControls.classList.add('hidden');
        clearErrors();
        
        // 聚焦到第一个单元格
        selectCell(0, 0);
        
        // 添加状态提示
        updateStatusMessage('<i class="fas fa-info-circle mr-2"></i>已进入手动录入模式，请在数独网格中输入数字', 'status-message text-blue-600 info-message');
        
        // 显示Toast提示
        showToast('<i class="fas fa-info-circle mr-2"></i>已进入手动录入模式，请在数独网格中输入数字', 'info');
        
        // 添加视觉反馈，让用户知道已经进入手动录入模式
        setTimeout(() => {
            sudokuGridContainer.classList.add('animate-pulse-border');
            setTimeout(() => {
                sudokuGridContainer.classList.remove('animate-pulse-border');
            }, 1000);
        }, 100);
        
        console.log("手动录入功能执行完成");
    } catch (error) {
        console.error("手动录入功能执行出错:", error);
    }
}

// 求解数独
function solveSudoku() {
    // 清除状态提示
    updateStatusMessage('', '');
    
    // 隐藏图片预览
    imagePreviewContainer.classList.add('hidden');
    
    updateStatusMessage('<i class="fas fa-circle-notch fa-spin mr-2"></i>正在求解...', 'status-message text-blue-600 info-message');
    
    // 模拟求解延迟
    setTimeout(() => {
        // 注意：在OCR识别或手动输入时，原始棋盘已经设置
        // 这里不需要再保存原始棋盘，否则会将用户输入的数字也视为原始题目数字
        
        // 检查数独是否有效
        if (!isValidSudoku(sudokuBoard)) {
            updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>数独题目无效，请检查输入', 'status-message text-red-600 text-lg error-message');
            return;
        }
        
        // 创建棋盘副本进行求解
        const boardCopy = JSON.parse(JSON.stringify(sudokuBoard));
        
        if (solveSudokuAlgorithm(boardCopy)) {
            // 求解成功
            sudokuBoard = boardCopy;
            updateBoardDisplay();
            updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>数独求解完成！', 'status-message text-green-600 text-lg success-message', true, 3000);
        } else {
            // 无解
            updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>数独无解！', 'status-message text-red-600 text-lg error-message');
        }
        
        // 隐藏逐步求解控件
        stepControls.classList.add('hidden');
    }, 800); // 模拟800毫秒的求解延迟
}

// 逐步求解数独
function solveStepByStep() {
    // 注意：在OCR识别或手动输入时，原始棋盘已经设置
    // 这里不需要再保存原始棋盘，否则会将用户输入的数字也视为原始题目数字
    
    // 检查数独是否有效
    if (!isValidSudoku(sudokuBoard)) {
        updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>数独题目无效，请检查输入', 'status-message text-red-600 text-lg error-message');
        return;
    }
    
    // 获取求解步骤
    solvingSteps = solveSudokuStepByStepAlgorithm(sudokuBoard);
    
    if (solvingSteps.length > 0) {
        currentStepIndex = 0;
        updateStatusMessage('<i class="fas fa-circle-notch fa-spin mr-2"></i>开始逐步求解...', 'status-message text-blue-600 text-lg info-message');
        stepControls.classList.remove('hidden');
        updateStepCounter();
    } else {
        updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>无法生成求解步骤', 'status-message text-red-600 text-lg error-message');
    }
}

// 显示上一步
function showPrevStep() {
    if (currentStepIndex > 0) {
        currentStepIndex--;
        applyStep(currentStepIndex);
        updateStepCounter();
    }
}

// 显示下一步
function showNextStep() {
    if (currentStepIndex < solvingSteps.length - 1) {
        applyStep(currentStepIndex);
        currentStepIndex++;
        updateStepCounter();
    } else if (currentStepIndex === solvingSteps.length - 1) {
        // 最后一步, 完成求解
        applyStep(currentStepIndex);
        currentStepIndex++;
        updateStepCounter();
        updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>逐步求解完成！', 'status-message text-green-600 text-lg success-message');
    }
}

// 应用步骤
function applyStep(stepIndex) {
    const step = solvingSteps[stepIndex];
    if (step.action === 'try' || step.action === 'backtrack') {
        sudokuBoard[step.row][step.col] = step.num;
        updateBoardDisplay();
    }
}

// 更新步骤计数器
function updateStepCounter() {
    stepCounter.textContent = `步骤 ${currentStepIndex}/${solvingSteps.length}`;
    prevStepBtn.disabled = currentStepIndex === 0;
    nextStepBtn.disabled = currentStepIndex === solvingSteps.length;
}

// 检查错误
function checkErrors() {
    const errors = findSudokuErrors(sudokuBoard);
    clearErrors();
    
    if (errors.length > 0) {
        errors.forEach(error => {
            const cell = document.querySelector(`[data-row="${error.row}"][data-col="${error.col}"]`);
            if (cell) {
                cell.classList.add('bg-red-200');
            }
        });
        updateStatusMessage(`<i class="fas fa-exclamation-circle mr-2"></i>发现 ${errors.length / 2} 处错误`, 'status-message text-red-600 text-lg error-message');
    } else {
        updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>未发现错误', 'status-message text-green-600 text-lg success-message', true, 3000);
    }
}

// 清除错误标记
function clearErrors() {
    document.querySelectorAll('[data-row][data-col]').forEach(cell => {
        cell.classList.remove('bg-red-200');
    });
    // 清除状态消息
    updateStatusMessage('', '');
}

// 清空棋盘
function clearBoard() {
    sudokuBoard = Array(9).fill().map(() => Array(9).fill(0));
    originalBoard = Array(9).fill().map(() => Array(9).fill(0));
    updateBoardDisplay();
    statusMessage.textContent = '';
    // 隐藏提示信息区域
    const hintArea = document.getElementById('hintArea');
    if (hintArea) hintArea.classList.add('hidden');
    difficultyDisplay.textContent = '难度: 未知';
    stepControls.classList.add('hidden');
    clearErrors();
    
    // 隐藏数独区域
    const sudokuSection = document.getElementById('sudokuSection');
    if (sudokuSection) {
        sudokuSection.classList.add('hidden');
    }
    
    // 显示模式选择区域
    const modeSelection = document.querySelector('.flex.flex-col.md\\:flex-row.justify-center.gap-6');
    if (modeSelection) {
        modeSelection.classList.remove('hidden');
    }
    
    // 移除模式按钮激活状态
    const manualModeBtn = document.getElementById('manualModeBtn');
    const imageModeBtn = document.getElementById('imageModeBtn');
    if (manualModeBtn) manualModeBtn.classList.remove('active');
    if (imageModeBtn) imageModeBtn.classList.remove('active');
    
    // 隐藏返回首页按钮
    const backToHomeBtn = document.getElementById('backToHomeBtn');
    if (backToHomeBtn) {
        backToHomeBtn.classList.add('hidden');
    }
    
    // 隐藏图片预览容器
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    if (imagePreviewContainer) {
        imagePreviewContainer.classList.add('hidden');
    }
    
    // 隐藏图片上传区域
    const imageUploadSection = document.getElementById('imageUploadSection');
    if (imageUploadSection) {
        imageUploadSection.classList.add('hidden');
    }
    
    // 显示上传区域
    const uploadArea = document.getElementById('uploadArea');
    if (uploadArea) {
        uploadArea.classList.remove('hidden');
    }
    
    // 隐藏图片预览在网格旁边
    const imagePreviewWrapper = document.getElementById('imagePreviewWrapper');
    if (imagePreviewWrapper) {
        imagePreviewWrapper.style.display = 'none';
    }
    if (previewImage) {
        previewImage.style.display = 'none';
    }
    
    // 重置文件输入以便可以再次选择相同文件
    if (fileUpload) {
        fileUpload.value = '';
    }
}

// 处理图片上传
function handleImageUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 显示上传状态
    updateStatusMessage('<i class="fas fa-circle-notch fa-spin mr-2"></i>正在识别图片中的数独...', 'status-message text-blue-600 info-message');
    
    const reader = new FileReader();
    reader.onload = function(e) {
        previewImage.src = e.target.result;
        // 显示网格旁边的预览图片
        const imagePreviewWrapper = document.getElementById('imagePreviewWrapper');
        if (imagePreviewWrapper && previewImage) {
            previewImage.style.display = 'block';
            imagePreviewWrapper.style.display = 'flex';
        }
        // 隐藏上传区域的预览容器
        if (imagePreviewContainer) {
            imagePreviewContainer.classList.add('hidden');
        }
        // 隐藏上传区域
        uploadArea.classList.add('hidden');
        // 显示操作按钮
        operationButtons.classList.remove('hidden');
        
        // 获取当前选择的OCR引擎
        loadConfig().then(config => {
            const ocrEngine = config.ocrEngine || 'opencv';
            
            // 根据配置选择OCR引擎
            if (ocrEngine === 'opencv' && typeof ocrWithOpenCV === 'function') {
                ocrWithOpenCV(e.target.result, config)
                    .then(grid => {
                        fillSudokuGrid(grid);
                        updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>数独识别完成！', 'status-message text-green-600 success-message');
                    })
                    .catch(err => {
                        console.error('OCR识别失败:', err);
                        updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>OCR识别失败: ' + err.message, 'status-message text-red-600 error-message');
                    });
            } else if (ocrEngine === 'baidu') {
                // 使用百度OCR
                if (typeof ocrWithBaidu === 'function') {
                    ocrWithBaidu(e.target.result);
                } else {
                    updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>百度OCR功能未找到', 'status-message text-red-600 error-message');
                }
            } else if (ocrEngine === 'tesseract') {
                // 使用Tesseract.js
                if (typeof ocrWithTesseract === 'function') {
                    ocrWithTesseract(e.target.result)
                        .then(grid => {
                            fillSudokuGrid(grid);
                            updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>数独识别完成！', 'status-message text-green-600 success-message');
                        })
                        .catch(err => {
                            console.error('OCR识别失败:', err);
                            updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>OCR识别失败: ' + err.message, 'status-message text-red-600 error-message');
                        });
                } else {
                    updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>Tesseract OCR功能未找到', 'status-message text-red-600 error-message');
                }
            } else if (typeof ocrWithOpenCV === 'function') {
                // 默认使用OpenCV
                ocrWithOpenCV(e.target.result, config)
                    .then(grid => {
                        fillSudokuGrid(grid);
                        updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>数独识别完成！', 'status-message text-green-600 success-message');
                    })
                    .catch(err => {
                        console.error('OCR识别失败:', err);
                        updateStatusMessage('<i class="fas fa-exclamation-circle mr-2"></i>OCR识别失败: ' + err.message, 'status-message text-red-600 error-message');
                    });
            } else {
                // 如果没有OCR功能，使用示例数据并给出提示
                // 示例数独数据
                const sampleSudoku = [
                    [5, 3, 0, 0, 7, 0, 0, 0, 0],
                    [6, 0, 0, 1, 9, 5, 0, 0, 0],
                    [0, 9, 8, 0, 0, 0, 0, 6, 0],
                    [8, 0, 0, 0, 6, 0, 0, 0, 3],
                    [4, 0, 0, 8, 0, 3, 0, 0, 1],
                    [7, 0, 0, 0, 2, 0, 0, 0, 6],
                    [0, 6, 0, 0, 0, 0, 2, 8, 0],
                    [0, 0, 0, 4, 1, 9, 0, 0, 5],
                    [0, 0, 0, 0, 8, 0, 0, 7, 9]
                ];
                
                // 填充数独网格
                fillSudokuGrid(sampleSudoku);
                
                if (statusMessage) {
                    statusMessage.innerHTML = '<i class="fas fa-exclamation-circle mr-2"></i>OCR功能未找到，使用示例数据';
                    statusMessage.className = 'status-message text-yellow-600 warning-message';
                    // 显示提示信息区域
                    const hintArea = document.getElementById('hintArea');
                    if (hintArea) hintArea.classList.remove('hidden');
                }
            }
        });
    };
    reader.readAsDataURL(file);
}

// 填充数独网格
function fillSudokuGrid(grid) {
    // 清空当前棋盘
    sudokuBoard = Array(9).fill().map(() => Array(9).fill(0));
    originalBoard = Array(9).fill().map(() => Array(9).fill(0));
    
    // 填充数独网格
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            sudokuBoard[row][col] = grid[row][col];
            originalBoard[row][col] = grid[row][col];
        }
    }
    
    // 更新显示
    updateBoardDisplay();
    updateDifficulty();
}

// 显示友好提示模态框
function showFriendlyAlert(message) {
    if (alertMessage && friendlyAlert) {
        alertMessage.textContent = message;
        friendlyAlert.classList.remove('hidden');
    } else {
        // 如果模态框元素不存在，回退到alert
        alert(message);
    }
}

// 隐藏友好提示模态框
function hideFriendlyAlert() {
    if (friendlyAlert) {
        friendlyAlert.classList.add('hidden');
    }
}

// 生成随机数独题目
function generateRandomSudoku() {
    console.log("点击了随机生成按钮");
    
    // 生成一个完整的数独解决方案
    const solution = generateSolvedSudoku();
    
    // 从完整解中挖洞，生成题目
    const puzzle = createPuzzleFromSolution(solution, 40); // 挖掉40个格子，中等难度
    
    // 清空当前棋盘但不隐藏数独区域
    sudokuBoard = Array(9).fill().map(() => Array(9).fill(0));
    originalBoard = Array(9).fill().map(() => Array(9).fill(0));
    updateBoardDisplay();
    statusMessage.textContent = '';
    difficultyDisplay.textContent = '难度: 未知';
    clearErrors();
    
    // 填充数独题目
    for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
            sudokuBoard[row][col] = puzzle[row][col];
            originalBoard[row][col] = puzzle[row][col];
        }
    }
    
    // 更新显示
    updateBoardDisplay();
    updateDifficulty();
    
    // 显示提示信息
    updateStatusMessage('<i class="fas fa-check-circle mr-2"></i>已生成中等难度数独题目', 'status-message text-green-600 success-message', true, 3000);
}

// 将generateRandomSudoku函数绑定到window对象，使其可以在全局范围内访问
window.generateRandomSudoku = generateRandomSudoku;

// 导出函数和变量
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        initializeSudokuBoard,
        createBoard,
        setupEventListeners,
        handleInput,
        handleKeyDown,
        selectCell,
        updateBoardDisplay,
        updateDifficulty,
        updateStatusMessage,
        showToast,
        showManualInput,
        solveSudoku,
        solveStepByStep,
        showPrevStep,
        showNextStep,
        applyStep,
        updateStepCounter,
        checkErrors,
        clearErrors,
        clearBoard,
        handleImageUpload,
        showFriendlyAlert,
        hideFriendlyAlert,
        generateRandomSudoku,
        sudokuBoard,
        originalBoard
    };
}